package com.example.blogsystem_ssm.controller;

import com.example.blogsystem_ssm.model.Blog;
import com.example.blogsystem_ssm.model.User;
import com.example.blogsystem_ssm.service.AuthorInfoService;
import com.example.blogsystem_ssm.service.BlogDeleteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class BlogDeleteController {
    @Autowired
    BlogDeleteService service;

    @Autowired
    AuthorInfoService authorInfoService;
    @RequestMapping(value = "/blogDelete")
    @Transactional
    public void blogDelete(@RequestParam Integer blogId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        Blog blog = authorInfoService.getBlog(blogId);
        if (blog == null){
            response.setContentType("text/html; charset=utf8");
            response.getWriter().write("您要删除的博客不存在，无法进行删除操作！");
            return ;
        }
        User user = (User) request.getSession(false).getAttribute("User");
        if(user.getUserId() != blog.getUserId()){
            // 虽然在前端中处理过这个问题，但是再稳一波，twin check 更保险！
            response.setContentType("text/html; charset=utf8");
            response.getWriter().write("非法删除操作！");
            return ;
        }
        service.delete(blogId);
        // 6、返回一个重定向响应
        response.sendRedirect("bloghome.html");
    }
}
